"""
智能日程管理助手 - 主程序入口
负责初始化各模块并启动应用程序
整合所有模块，提供完整的日程管理功能
"""
import tkinter as tk
from tkinter import messagebox
import logging
import os
import sys
import traceback

# 导入自定义模块
from database import DatabaseManager
from config import ConfigManager
from network_sim import NetworkSimulator
from reminder_service import ReminderManager
from file_export import FileExporter
from gui import ScheduleGUI
from utils import ensure_directory_structure, backup_database, cleanup_old_data
from program_info import get_program_info


def setup_logging(config):
    """配置日志系统"""
    try:
        log_level = config.get("system.log_level", "INFO")
        log_dir = "data/logs"
        
        # 确保日志目录存在
        os.makedirs(log_dir, exist_ok=True)
        
        # 设置日志级别
        level = getattr(logging, log_level.upper(), logging.INFO)
        
        # 配置日志
        logging.basicConfig(
            level=level,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(os.path.join(log_dir, 'app.log'), encoding='utf-8'),
                logging.StreamHandler(sys.stdout)
            ]
        )
        
        # 设置第三方库的日志级别
        logging.getLogger('sqlite3').setLevel(logging.WARNING)
        
        logger = logging.getLogger(__name__)
        logger.info("日志系统配置完成")
        return True
        
    except Exception as e:
        print(f"配置日志系统失败: {e}")
        return False


def initialize_system(config):
    """初始化系统"""
    logger = logging.getLogger(__name__)
    
    try:
        # 确保目录结构完整
        ensure_directory_structure()
        logger.info("目录结构初始化完成")
        
        # 数据库备份（如果配置开启）
        if config.get("database.backup_on_start", True):
            db_path = config.get("database.path", "data/schedules.db")
            backup_path = backup_database(db_path)
            if backup_path:
                logger.info(f"数据库备份完成: {backup_path}")
            else:
                logger.warning("数据库备份失败")
        
        # 清理旧数据
        auto_cleanup_days = config.get("database.auto_cleanup_days", 30)
        if auto_cleanup_days > 0:
            cleaned_count = cleanup_old_data(auto_cleanup_days)
            logger.info(f"自动清理完成，删除了 {cleaned_count} 个旧文件")
        
        return True
        
    except Exception as e:
        logger.error(f"系统初始化失败: {e}")
        return False


def show_error_dialog(title, message, parent=None):
    """显示错误对话框"""
    try:
        if parent and hasattr(parent, 'root'):
            messagebox.showerror(title, message, parent=parent.root)
        else:
            messagebox.showerror(title, message)
    except:
        # 如果GUI不可用，打印到控制台
        print(f"错误: {title} - {message}")


def main():
    """主函数"""
    # 程序信息
    program_info = get_program_info()
    print(f"启动 {program_info['name']} v{program_info['version']}")
    
    # 初始化变量
    app = None
    net_sim = None
    reminder_manager = None
    config = None
    
    try:
        # 初始化配置管理器
        config = ConfigManager()
        print("配置管理器初始化成功")
        
        # 配置日志系统
        if not setup_logging(config):
            print("警告: 日志系统配置失败，将继续运行")
        
        logger = logging.getLogger(__name__)
        logger.info("=" * 50)
        logger.info(f"启动 {program_info['name']} v{program_info['version']}")
        logger.info(f"Python版本: {program_info['python_version']}")
        logger.info(f"工作目录: {os.getcwd()}")
        
        # 初始化系统
        if not initialize_system(config):
            logger.warning("系统初始化过程中遇到问题")
        
        # 初始化数据库
        db_path = config.get("database.path", "data/schedules.db")
        db_manager = DatabaseManager(db_path)
        logger.info("数据库管理器初始化成功")
        
        # 启动网络模拟服务
        net_sim = NetworkSimulator(port=config.get("network.port", 8888))
        if config.get("network.auto_start_server", True):
            if net_sim.start_server():
                logger.info("网络模拟服务已启动")
            else:
                logger.warning("网络模拟服务启动失败")
        
        # 创建提醒管理器
        reminder_manager = ReminderManager(db_manager)
        logger.info("提醒管理器初始化成功")
        
        # 创建文件导出器
        file_exporter = FileExporter(db_manager)
        logger.info("文件导出器初始化成功")
        
        # 创建并启动GUI
        logger.info("正在初始化GUI界面...")
        app = ScheduleGUI(db_manager, net_sim, reminder_manager, file_exporter, config)
        logger.info("GUI界面初始化成功")
        
        # 进入主循环
        logger.info("程序启动完成，进入主循环")
        app.run()
        
        logger.info("程序正常退出")
        
    except ImportError as e:
        error_msg = f"模块导入失败: {e}\n请确保所有必需文件都在同一目录下。"
        print(error_msg)
        show_error_dialog("启动错误", error_msg)
        
    except Exception as e:
        error_msg = f"程序启动失败: {str(e)}"
        print(error_msg)
        traceback.print_exc()
        
        # 记录详细错误信息
        if 'logger' in locals():
            logger.error(f"程序启动失败: {e}", exc_info=True)
        else:
            # 如果日志系统还没初始化，创建临时日志
            try:
                os.makedirs("data/logs", exist_ok=True)
                with open("data/logs/startup_error.log", "w", encoding="utf-8") as f:
                    f.write(f"启动错误: {error_msg}\n")
                    f.write(traceback.format_exc())
            except:
                pass
        
        show_error_dialog("启动错误", f"{error_msg}\n\n详细信息已保存到 data/logs/startup_error.log")
        
    finally:
        # 清理资源
        cleanup_resources(net_sim, reminder_manager, config)

def cleanup_resources(net_sim, reminder_manager, config):
    """清理资源"""
    logger = None
    try:
        # 获取logger，如果日志系统已初始化
        logger = logging.getLogger(__name__)
    except:
        pass
    
    try:
        if net_sim:
            net_sim.stop_server()
            if logger:
                logger.info("网络服务已停止")
    except Exception as e:
        if logger:
            logger.error(f"停止网络服务时出错: {e}")
    
    try:
        if reminder_manager:
            stopped_count = reminder_manager.stop_all_services()
            if logger:
                logger.info(f"已停止 {stopped_count} 个提醒服务")
    except Exception as e:
        if logger:
            logger.error(f"停止提醒服务时出错: {e}")
    
    try:
        if config:
            config._save_config()
            if logger:
                logger.info("配置已保存")
    except Exception as e:
        if logger:
            logger.error(f"保存配置时出错: {e}")
    
    if logger:
        logger.info("程序退出完成")
        logging.shutdown()



if __name__ == "__main__":
    # 设置异常处理
    def handle_exception(exc_type, exc_value, exc_traceback):
        """处理未捕获的异常"""
        if issubclass(exc_type, KeyboardInterrupt):
            # 键盘中断，正常退出
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        
        # 记录异常
        error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
        print(f"未处理的异常:\n{error_msg}")
        
        # 尝试记录到日志文件
        try:
            with open("data/logs/crash.log", "a", encoding="utf-8") as f:
                f.write(f"崩溃时间: {__import__('datetime').datetime.now()}\n")
                f.write(error_msg)
                f.write("\n" + "="*50 + "\n")
        except:
            pass
        
        # 显示错误对话框
        try:
            messagebox.showerror(
                "程序错误", 
                f"程序遇到意外错误:\n\n{exc_type.__name__}: {exc_value}\n\n详细信息已保存到日志文件。"
            )
        except:
            pass
    
    # 设置全局异常处理
    sys.excepthook = handle_exception
    
    # 运行主程序
    main()